var local = {},
    leaveConfig = {},
    evtHandler = {},
    curConfigItem,
    curPartialDays,
    isSameday,
    submitRule,
    showDate,
    fixedDate,
    params,
    hideHalfDay = false,
    myiscroll = null,
    leave_hour_config = {
        "N" : {
            "l_sHour" : "hide",
            "l_eHour" : "hide",
            "l_hour" : "hide"
        },
        "A" : {
            "l_sHour" : "hide",
            "l_eHour" : "hide",
            "l_hour" : "show"
        },
        "S" : {
            "l_sHour" : "show",
            "l_eHour" : "hide",
            "l_hour" : "hide"
        },
        "E" : {
            "l_sHour" : "hide",
            "l_eHour" : "show",
            "l_hour" : "hide"
        },
        "B" : {
            "l_sHour" : "show",
            "l_eHour" : "show",
            "l_hour" : "hide"
        }
    };
function init (){
	leftmenu("#leftmenu","#container");
    loadLeaveConfig();
    //滚动条
    iscroll();
    initLocalNode();
    bindEvent();
    $(window).resize(function(){//当窗口大小改变时自动重新计算
		iscroll();
		if((-myiscroll.maxScrollY)>0){
			myiscroll.scrollTo(0,myiscroll.maxScrollY,0,false);
		}
	});
    
    $("#errorMask").on("tap",function(){
		$("#errorMask").hide();
	});
	$("#noteMask").on("tap",function(){
		$("#noteMask").hide();
	});
	$("#selectType").on("tap",function(){
		_fadeDown($("#qj-select-layer"), function(){
            local.mainLayer.show();
            local.footer.show();
        });
	});
	$("#selectFzr").on("tap",function(){
		_fadeDown($("#half-day-layer"), function(){
            local.mainLayer.show();
            local.footer.show();
        });
	});
	
	//$(document).on("tap",function(e){
	//	if(e.target.id !="i_reason"){
	//		$("#i_reason").blur();
	//	}
	//}).on("swipe",function(){$("#i_reason").blur();});
}

function initLocalNode(){
    local.noteMask = $("#noteMask");
    local.container = $("#container");
    local.mainLayer = $("#qj-main-layer");
    local.footer = $("#footer");
}

/**
 * 初始化事件绑定
 */
function bindEvent () {
    initEvent();
    evtHandler.handleEvent = function (e){
        var node = $(e.target), et;
        if(e.target.tagName == "A")return;
        e.preventDefault();
        et = node.attr("et");
        if(!et){
            node = node.parent(), et = node.attr("et");
            if(!et){
                return;
            }
        }
        e.stopPropagation();
        if(et.indexOf(e.type) == 0){
            evtHandler[et.split(":")[1]](node);
        }
    };
    local.container.on("tap change input click", evtHandler.handleEvent);
}	
/**
 * 定义所有事件
 */
var obj = null;
function initEvent () {
	
	$("#mydate").scroller('destroy').scroller({
		preset: 'date',
		dateFormat: 'yy/mm/dd',
		dateOrder: 'yymmdd',
		minDate: new Date(2002, 3, 10, 9, 22),
		maxDate: new Date(2030, 7, 30, 15, 44),
		theme: 'ios',
		mode: 'scroller',
		lang: 'zh',
		display: 'bottom',
		animate: 'slideup',
		onSelect:function(){
			var fixedDate = $(this).attr("fixed-date");
			if(fixedDate){
				$(obj).children(".info-list-cont").children("input").val(fixedDate);
			}else{
				$(obj).children(".info-list-cont").children("input").val($(this).val());
				initHalfDayConfig("");
			}
		}
	});
	$("#l_sDate,#l_eDate,#l_date").on("tap",function(e){
		$("#mydate").scroller('show');
		$(".dwo").css("background-color","#000");
	    $(".dwo").css("opacity",".5");
	    $(".dwo").css("z-index","1000");
	    obj = this;
	});
	// 选择日期
	//evtHandler.selectDate = function(node){
   	//	showDate = node.attr("id");
   	//	$('#'+showDate).scroller('show');
   //	}
    // 弹出气泡:请假说明
    evtHandler.showBubble = function(node){
    	var _index = node.attr("data-index");
    	$("#leaveMark").html("<div align=\"center\">"+leaveConfig[_index].leaveType+"</div>"+leaveConfig[_index].leaveMark);
        local.noteMask.show();
    }
    // 隐藏气泡
    evtHandler.hideBubble = function(){
        local.noteMask.hide();
    }
    //弹出请假类型选择
    evtHandler.viewLeaveType = function(){
        local.mainLayer.hide();
        local.footer.hide();
        _fadeUp($("#qj-select-layer"));
		//滚动条
	    var wh = $(window).height()-90; 
		$("#divSelectType").css("height",wh+"px");
		var myiscroll2 = new iScroll("divSelectType",{bounce:false});
        
    }
    // 选择请假类型
    evtHandler.selectLeavetype = function(node){
        var _index = node.attr("data-index");
        curConfigItem = leaveConfig[_index];
        // 及时更新其他选项
        renderOptions(($("#i_type").text()!=node.text()));
        $("#i_type").text(node.text());
        
        _fadeDown($("#qj-select-layer"), function(){
            local.mainLayer.show();
            local.footer.show();
            iscroll();
        });
        iscroll();
    }
    // 选择 "非整日请假"
    evtHandler.viewHalfDay = function(){
        local.mainLayer.hide();
        local.footer.hide();
        _fadeUp($("#half-day-layer"));
        iscroll();
    }
    // "非整日请假"列表选中事件
    evtHandler.selectHalfDay = function(node){
        curPartialDays = node.attr("data-key");
        $("#i_halfDay1").text(node.text());
        _fadeDown($("#half-day-layer"), function(){
            local.mainLayer.show();
            local.footer.show();
            iscroll();
        });
        renderLeaveHour();
        //滚动条
        iscroll();
    }
    // 非整日请假切换选择触发事件
    evtHandler.onChangeHalfDay = function(node){
        var _state = node.text();
        if(_state == "整天"){
            curPartialDays = "S";
            node.text((curConfigItem.leave_is_hour == "H") ? "非整天" : "半天");
            iscroll();
        } else {
            curPartialDays = "N";
            node.text("整天");
            iscroll();
        }
        renderLeaveHour();
        //滚动条
        iscroll();
    }
    $("#i_reason").on("focus", function(){
	    if($(this).hasClass("textarea-max-height")) return;
	    $(this).removeClass("textarea-min-height").addClass("textarea-max-height");
//	    myiscroll.scrollToElement(this,0);
	}).on("blur", function(){
	    if(this.value === ''){
	         $(this).removeClass("textarea-max-height").addClass("textarea-min-height");
	    }
		iscroll();
	});

	
	$(".div-radio-list").find(".div-radio-item").on("tap", function(){
	    $(this).addClass("item-checked").siblings().removeClass("item-checked");
	})

    // 起止事件改变时间
    //evtHandler.onDateChange = initHalfDayConfig;

    // 提交请假
    evtHandler.submitApply = function(){
        if(!validateForm(submitRule)){
            return;
        }
        params = {
            pinTakeNum : curConfigItem.leaveType_code,
            partialDays : curPartialDays,
            marrySRCH : $("#i_firstMarry").text()=="初婚" ? 1 : 2,
            method:"askforwork"
        };
        // 遍历各控件的值
        $(".i-option").forEach(function(node){
            var key = node.getAttribute("param-name");
            if(key){
                params[key] = node.value;
            }
        });
        // 日期
        var dt = $("#i_date").val();
        if($("#l_date")[0].style.display!="none" && dt!=""){
            params.bgnDT = dt;
            params.endDT = dt;
        }

        // ********** 测试 打印 ***********
//        var paramString = "";
//        for(var i in params){
//            paramString += (i + " : " + params[i] + "\n");
//        }
//        alert(paramString);

		//autoClosePrompt();
        // 提交
        //$("#CheckPrompt").css("display","block");//
        $("#CheckPrompt").show();//显示加载图片
        $.ajax({
            type : "post",
            //url : "addLeave.do",
            url: mpsurl+"/mobile/leave/askForLeave.do",
            dataType : "json",
            data:params,
            success : function(json){
        		$("#CheckPrompt").hide();//
            	if(json.resultCode == "500600"){
            		if(json.flag == "S"){
            			var unittype ="小时";
            			var comput = json.compute;
            			if(json.unit_type=="D")
            				unittype = "天";
            			if(comput.substr(0,1)==".")
            				comput = "0"+comput;
	                    $("#confirmText").html("您本次请假共" + comput + unittype + "。<br>审批人：" + json.assess_name +"。");
	                    $("#confirmMask").show();
                    }else{
                    	errorMask(json.error_msg);
//                    	autoClosePrompt(json.error_msg);
                    }
                } else{
                	var tourl = "/mobile/mywork/sqwork.html";
                	checkLogin(json.resultCode,tourl,json.resultMessage);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            	$("#CheckPrompt").hide();
//				errorMask(errorThrown);
            	autoClosePrompt("网络异常");
            }
        });
    }
    //是否初婚
    evtHandler.onChangeMarry = function(node){
        (node.text() == "初婚") ? node.text("非初婚") : node.text("初婚");
    }
    evtHandler.cancelSubmit = function(){
        $("#confirmMask").hide();
    }
    evtHandler.confirmSubmit = function(){
        // 提交
        $("#confirmMask").hide();
        //$("#CheckPrompt").css("display","block");//
        $("#CheckPrompt").show();//显示加载图片
        $.ajax({
            type : "post",
            url: mpsurl+"/mobile/leave/addLeave.do",
            dataType : "text",
            data:params,
            success : function(json){
        		$("#CheckPrompt").hide();//
            	json = eval("("+json+")");
                if(json.resultCode=="500600"){
                    if(json.value.FLAG == "S"){
//                        location.href = "/mobile/mywork/qjwork.html";
						autoClosePrompt("请假成功");
                        setTimeout(function(){
                        	gotoLocation("/mobile/mywork/qjwork.html","")
                        },2000);
                        return;
                    }else{
                        errorMask(json.value.HR_SSTEXT_TEXT);
                    }
                }else{
                	var tourl = "/mobile/mywork/sqwork.html";
                	checkLogin(json.resultCode,tourl,json.resultMessage);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            	$("#CheckPrompt").hide();
//                errorMask(errorThrown);
                autoClosePrompt("网络异常");
            }
        });
    }
}

// 浮层-从下往上-弹出
function _fadeUp(node, callback){
    node.css("-webkit-transform", "translate3d(0px, " + window.innerHeight + "px, 0px);");
    node.show().animate({
            "-webkit-transform": "translate3d(0px, 0px, 0px);"}
        , 300, "ease-in-out", callback);
}
// 浮层-从上往下-消失
function _fadeDown(node, callback) {
    node.animate({
            "-webkit-transform": "translate3d(0px, " + window.innerHeight + "px, 0px);"}
        , 300, "ease-in-out", function(){
            node.hide();
            callback();
        });
}

/**
 * 获取请假各字段配置
 */
function loadLeaveConfig () {
	$("#CheckPrompt").show();
	$("#iscrollContent .row-info").hide();
	iscroll();
    $.ajax({
    	type : "post",
        url: mpsurl+"/mobile/leave/queryLeaveType.do",
        dataType : "json",
        data:{method:"qjtype"},
        success : function(json){
        	if(json.resultCode=="500600"){
	            leaveConfig = json.value;
	            if(leaveConfig.length==0){
	            	$("#iscrollContent .row-info ul").remove();
	            	$("#CheckPrompt").hide();
	            	$("#iscrollContent .row-info").append("<div class=\"no-record-prompt\"><div class=\"prompt-icon-txt\">暂无请假类型</div></div>");
	            	$("#footer").hide();
	            }else{
	            	var descrUrl = decodeURI(getQueryParam("descr"),"utf-8");
	            	leaveConfig = json.value;
				    for(var i in leaveConfig){
				        var lc = leaveConfig[i];
				        lc.leaveType = lc.leaveType.replace(/\d+\s+/g, "");
				        /*
				        if (lc.leaveType == "临时因公外出"){
				            curConfigItem = lc;
				        }*/
				    }
				    if(descrUrl!=""&&(descrUrl.indexOf("漏打卡")!=-1)){
				    	for(var i in leaveConfig){
					        var lc = leaveConfig[i];
					        lc.leaveType = lc.leaveType.replace(/\d+\s+/g, "");
					        if (lc.leaveType == "漏打卡"){
					            curConfigItem = lc;
					        }
				    	}
				    }else{
				    	curConfigItem = leaveConfig[0];
				    }
				    $("#iscrollContent .row-info").show();
				    //$("#optionList").show();
                    $("#CheckPrompt").hide();
                    $("#footer").show();
                    iscroll();
		            renderLeaveTypeList();
		            renderOptions(true);
	            }
            }else{
            	$("#iscrollContent .row-info").show();
            	$("#CheckPrompt").hide();
            	$("#iscrollContent .row-info ul").remove();
	            $("#iscrollContent .row-info").append("<div class=\"no-record-prompt\">"+
	            	"<div class=\"prompt-icon-txt\">"+json.resultMessage+"</div></div>");
	            $("#footer").hide();
	            var tourl = "/mobile/mywork/sqwork.html";
                checkLogin(json.resultCode,tourl,json.resultMessage);
            }
        }
    });
    //$("#footer").show();
    iscroll();
}

/**
 * 渲染请假原因选择列表
 */
function renderLeaveTypeList (){
    var _tpl = $("#leave-type-tpl").html(), dot = doT.template(_tpl);
    $("#qjTypeList").html(dot(leaveConfig));
    $("#i_type").text(curConfigItem.leaveType);
}

/**
 * 初始化非整日选择列表样式
 */
function initHalfDayConfig (param) {
    if(curConfigItem.leave_is_days == "N" || hideHalfDay){ // 特定的请假类型才能提供小时选择
        return;
    }
    isSameday = $("#i_sDate").val() == $("#i_eDate").val();
    if(isSameday){ // 起至日期同一天
        $("#l_halfDay1").hide();
        $("#l_halfDay2").show();
    	if(param&&param.indexOf("漏打卡")==-1&&param.indexOf("旷工")==-1){
	        $("#i_halfDay2").text("非整天");
	        curPartialDays = "S";//默认选整天
    	}else{
	        $("#i_halfDay2").text("整天");
	        curPartialDays = "N";//默认选整天
        }
    } else { // 起至日期不同一天
        $("#l_halfDay1").show();
        $("#l_halfDay2").hide();
        curPartialDays = "N";//默认选头一条
        $("#i_halfDay1").text("每日整天请假");
    }
    // 渲染请假时间
    renderLeaveHour();
    iscroll();
}

/**
 * 根据非整日选择情况渲染请假小时数
 */
function renderLeaveHour (){
    if(curConfigItem.leave_is_hour != "H"){ // 特定的请假类型才能提供小时选择
        return;
    }
    var _curHourConfig = leave_hour_config[curPartialDays];
    for(var c in _curHourConfig){
        $("#"+c)[_curHourConfig[c]]();
    }
    iscroll();
}

/**
 * 渲染请假类型以外的其他选项
 */
function renderOptions(typeChanged) {
    // 切换请假类型, 初始化所有控件
    var parame0 = getQueryParam("qjdate");
    var parame1 = getQueryParam("qjTime");
    var parame2 = decodeURI(getQueryParam("descr"),"utf-8");
    var date = "";
    var _hours = "";
    var _desc = "";
    if(parame0.length > 0){
    	date = parame0;
    	_hours = parame1;
    	_desc = parame2;
    }
    var _type ="";
    if(typeChanged){
        $(".l-option").hide(); // 先隐藏所有控件
        $(".i-option").val("");
        hideHalfDay = false;
        var iNodes = $("input[readonly]");
        for(var i = 0; i< iNodes.length; i++){
        	if(!$(iNodes[i]).hasClass("dateSelector")){
            	iNodes[i].removeAttribute("readonly");
        	}
        }
        //$(".i-option").attr("fixed-date", ""); // 解除日期控件不可编辑
        if(date){
        	date = date.replace("-","/").replace("-","/");
            $("#i_date").val(date); // 不可编辑
            $("#i_sDate").val(date); // 不可编辑
            $("#i_eDate").val(date); // 不可编辑
            if(_hours&&_desc.indexOf("漏打卡")==-1&&_desc.indexOf("旷工")==-1){
            	$("#i_sHour").val((_hours.indexOf(".")==0?"0"+_hours:_hours));
            }
        } 
        $("#i_date").attr("fixed-date", "");
        $("#i_sDate").attr("fixed-date", "");
        $("#i_eDate").attr("fixed-date", "");
        $("#t_sHour").text("开始日小时数：");
    }
    _type = curConfigItem.leaveType;
    switch(_type){
        case "青年节":
        	hideHalfDay = true;
            $("#l_date, #l_sHour").show();
            var theDay = new Date().getFullYear() + "/05/04";
            $("#i_date").val(theDay).attr("fixed-date", theDay); // 不可编辑
            $("#t_sHour").text("请假天数");
            $("#i_sHour").val("0.5").attr("readOnly", "true"); // 不可编辑
            curPartialDays = "S";
            break;
        case "妇女节":
        	hideHalfDay = true;
            $("#l_date, #l_sHour").show();
            var theDay = new Date().getFullYear() + "/03/08";
            $("#i_date").val(theDay).attr("fixed-date", theDay); // 不可编辑
            $("#t_sHour").text("请假天数");
            $("#i_sHour").val("0.5").attr("readOnly", "true"); // 不可编辑
            curPartialDays = "S";
            break;
        case "义务献血假":
        	hideHalfDay = true;
            $("#l_date, #l_sHour").show();
            $("#t_sHour").text("请假天数");
            $("#i_sHour").val("0.5").attr("readOnly", "true"); // 不可编辑
            curPartialDays = "S";
            submitRule = {
                "i_date" : {parentId:"l_date", itemName:"日期", required:true, emptyMsg:"请输入日期"}
            };
            break;
        case "生日弹性考勤":
        	hideHalfDay = true;
            $("#l_date, #l_sHour").show();
            $("#t_sHour").text("请假小时数");
            $("#i_sHour").val("2.00");
            curPartialDays = "S";
            submitRule = {
                "i_date" : {parentId:"l_date", itemName:"日期", required:true, emptyMsg:"请输入日期"},
                "i_sHour" : {reg:/^\d*\.?\d*$/,errMsg:"请输入数字",parentId:"l_sHour", itemName:"请假小时数", required:true, minVal:0.1, maxVal:2, emptyMsg:"请输入请假小时数", valErrMsg:"生日弹性考勤每日最多请假2小时"}
            };
            break;
        case "孕妇工间休息假":
        	hideHalfDay = true;
            $("#l_sDate, #l_eDate, #l_hour").show();
            $("#i_hour").val("0.5").attr("readOnly", "true"); // 不可编辑
            curPartialDays = "A";
            submitRule = {
                "i_sDate" : {parentId:"l_sDate", itemName:"开始日期", required:true, emptyMsg:"请输入开始日期"},
                "i_eDate" : {parentId:"l_eDate", itemName:"结束日期", required:true, emptyMsg:"请输入结束日期"}
            };
            break;
        case "哺乳假":
        	hideHalfDay = true;
            $("#l_sDate, #l_eDate, #l_hour").show();
            $("#i_hour").val("1.0");
            curPartialDays = "A";
            submitRule = {
                "i_sDate" : {parentId:"l_sDate", itemName:"开始日期", required:true, emptyMsg:"请输入开始日期"},
                "i_eDate" : {parentId:"l_eDate", itemName:"结束日期", required:true, emptyMsg:"请输入结束日期"},
                "i_hour" : {reg:/^\d*\.?\d*$/,errMsg:"请输入数字",parentId:"l_hour", itemName:"每日小时数", required:true, minVal:0.01, maxVal:1, emptyMsg:"请输入每日小时数", valErrMsg:"哺乳假每日最多请假1小时"}
            };
            break;
        case "婚假":
            $("#l_sDate, #l_eDate, #l_firstMarry").show();
            curPartialDays = "N";
            break;
        case "出差":
        case "漏打卡":
        case "特殊岗位考试假":
//        case "婚假":
        case "产假":
        case "看护假":
        case "丧假":
        case "忘带工卡":
        case "异地干部特殊休假":
            $("#l_sDate, #l_eDate").show();
            curPartialDays = "N";
            submitRule = {
                "i_sDate" : {parentId:"l_sDate", itemName:"开始日期", required:true, emptyMsg:"请输入开始日期"},
                "i_eDate" : {parentId:"l_eDate", itemName:"结束日期", required:true, emptyMsg:"请输入结束日期"}
            };
            break;

        default :
            $("#l_sDate").show();
            $("#l_eDate").show();
            initHalfDayConfig(_desc);
            submitRule = {
                "i_sDate" : {parentId:"l_sDate", itemName:"开始日期", required:true, emptyMsg:"请输入开始日期"},
                "i_eDate" : {parentId:"l_eDate", itemName:"结束日期", required:true, emptyMsg:"请输入结束日期"},
                "i_sHour" : {reg:/^\d*\.?\d*$/,errMsg:"请输入数字",parentId:"l_sHour", itemName:"开始日小时数", required:false, minVal:0.01, maxVal:8.0, emptyMsg:"请输入开始日小时数", valErrMsg:"一天请假最多8小时"},
                "i_eHour" : {reg:/^\d*\.?\d*$/,errMsg:"请输入数字",parentId:"l_eHour", itemName:"结束日小时数", required:false, minVal:0.01, maxVal:8.0, emptyMsg:"请输入结束日小时数", valErrMsg:"一天请假最多8小时"},
                "i_hour" : {reg:/^\d*\.?\d*$/,errMsg:"请输入数字",parentId:"l_hour", itemName:"每日小时数", required:false, minVal:0.01, maxVal:8.0, emptyMsg:"请输入每日小时数", valErrMsg:"一天请假最多8小时"}
            };
            break;
    }
    iscroll();
	function getQuery (name,url){
        //参数：变量名，url为空则表从当前页面的url中取
        var u  = arguments[1] || window.location.search.replace("&amp;", "&"),
            reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"),
            r = u.substr(u.indexOf("\?")+1).match(reg);
        return r!=null?r[2]:"";
    }
}
function iscroll(){
	var wh = $(window).height()-110-112; 
	if(myiscroll instanceof iScroll)
		myiscroll.destroy();
	$("#content").css("height",wh+"px");
	myiscroll = new iScroll("content",{bounce:false});
}
function autoClosePrompt(msg){
	var obj = document.getElementById("validateBox2");
	if(null == obj){
		var promptBox = 
			"<div id='validateBox2' style='position: fixed;left: 20%;bottom: 15%;width: 60%;z-index: 1000;'>"+
			"<div style='position: absolute;width: 100%;height: 100%;background: #000;-webkit-border-radius: 8px;border-radius: 8px;opacity: .6;z-index: 1;'>"+
			"</div>"+
			"<div style='position: relative;display: -webkit-box;color: #fff;min-height:20px;-webkit-box-orient: horizontal;-webkit-box-pack: center;padding:5px 8px;font-size: 28px;text-align: center;z-index: 2;'>"+
			msg+"</div>"+
			"</div>";
		$("body").append(promptBox);
		// 定时关闭提示框
		setTimeout(function(){
			$("#validateBox2").remove("slow");
		},5000);
	}
}